import hashlib
from database import session_maker
from model.users import User


def init_admin_account(password):
    user = 'admin'
    role = 'superadmin'
    # password = "".join(random.sample('1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()', 12))
    password_md5 = hashlib.md5(password.encode()).hexdigest()
    with session_maker() as session:
        count = session.query(User).filter(User.username == user).count()
        if count == 0:
            print("初始化admin账户，密码为: " + password)
            user_obj = User(username=user, role=role, password=password_md5)
            session.add(user_obj)


def add_user(username, role, password):
    # user 普通用户
    # auditor 审批员
    # ops 运维员
    # superadmin 超级管理员
    role_sets = ['user', 'auditor', 'admin', 'superadmin']
    if role not in role_sets:
        print("不合法的role，无法创建此用户")
        return
    password_md5 = hashlib.md5(password.encode()).hexdigest()
    with session_maker() as session:
        count = session.query(User).filter(User.username == username).count()
        if count == 0:
            user_obj = User(username=username, role=role, password=password_md5)
            session.add(user_obj)
            print("user added!")
        if count >= 1:
            print("user already exist!")


def reset_password(username, password):
    password = hashlib.md5(password.encode()).hexdigest()
    with session_maker() as session:
        count = session.query(User).filter(User.username == username).count()
        if count == 0:
            print("no such user!")
            return
        if count == 1:
            session.query(User).filter(User.username == username).update({"password": password})
            print("password changed!")
        if count > 1:
            print("more than one user!")
